/**
 * 工作单位：IT创新工作室
 * 文件名：MqttService
 * 作者：cheru
 * 日期：2019/11/21 0:53
 */
package com.itgzs.back.service;

import com.itgzs.back.bean.Toggle;
import com.itgzs.back.mapper.ToggleMapper;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class ToggleService {

    public static final String MQTT_BROKER_HOST = "tcp://192.168.137.41:1883";
    public static final String MQTT_CLIENT_ID = "toggle";

    //订阅的主题
    public static final String[] MQTT_TOPICS = {
            "itgzs/led_light/older",
            "itgzs/led_color/transform/older",
            "itgzs/curtain/older",
            "itgzs/ir_tran/air_cond/older",
    };

    public static final String USERNAME = "admin";
    public static final String PASSWORD = "password";

    private volatile static MqttClient mqttClient;
    private static MqttConnectOptions options;
    private static MqttTopic topic;
    private static MqttMessage message;

    private static HashMap<String, String> hashMap;

    static {
        hashMap = new HashMap<>();
        hashMap.put("led", "0");
        hashMap.put("colorLed", "0");
        hashMap.put("curtain", "0");
        hashMap.put("degree", "0");

        try {
            // host为主机名，clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，
            // MemoryPersistence设置clientid的保存形式，默认为以内存保存
            mqttClient = new MqttClient(MQTT_BROKER_HOST, MQTT_CLIENT_ID, new MemoryPersistence());
            // 配置参数信息
            options = new MqttConnectOptions();
            // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，
            // 这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(true);
            // 设置用户名
            options.setUserName(USERNAME);
            // 设置密码
            options.setPassword(PASSWORD.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);

            // 推送消息
            message = new MqttMessage();

            message.setQos(2);
            message.setRetained(false);

            //连接
            mqttClient.connect(options);

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private Toggle toggle;

    @Autowired
    private ToggleMapper toggleMapper;

    @Scheduled(fixedRate = 2000)
    public void toggleData() {

        try {
            toggle = toggleMapper.selectToggle();
            System.out.println(toggle);

            for(String MQTT_TOPIC : MQTT_TOPICS){

                topic = mqttClient.getTopic(MQTT_TOPIC);

                switch (MQTT_TOPIC){
                    case "itgzs/led_light/older" :
                        if(!toggle.getLed().equals(hashMap.get("led"))){
                            hashMap.put("led", toggle.getLed());
                            message.setPayload(toggle.getLed().getBytes());
                            topic.publish(message);

                            topic = mqttClient.getTopic("itgzs/mp3player/older");
                            if("0".equals(toggle.getLed())){
                                message.setPayload("9".getBytes());
                            }else if("1".equals(toggle.getLed())){
                                message.setPayload("7".getBytes());
                            }else{
                                message.setPayload("8".getBytes());
                            }
                            topic.publish(message);
                        }
                        break;
                    case "itgzs/led_color/transform/older" :
                        if(!toggle.getColorLed().equals(hashMap.get("colorLed"))){
                            hashMap.put("colorLed", toggle.getColorLed());
                            message.setPayload(toggle.getColorLed().getBytes());
                            topic.publish(message);

                            topic = mqttClient.getTopic("itgzs/mp3player/older");
                            if("2".equals(toggle.getColorLed())){
                                message.setPayload("10".getBytes());
                            }else if("1".equals(toggle.getColorLed())){
                                message.setPayload("14".getBytes());
                            }else if("0".equals(toggle.getColorLed())){
                                message.setPayload("15".getBytes());
                            }
                            topic.publish(message);
                        }
                        break;
                    case "itgzs/curtain/older" :

                        if(!toggle.getCurtain().equals(hashMap.get("curtain"))){

                            hashMap.put("curtain", toggle.getCurtain());

                            if("0".equals(toggle.getCurtain())){
                                message.setPayload("-3".getBytes());
                            }else if("1".equals(toggle.getCurtain())){
                                message.setPayload("3".getBytes());
                            }else if(toggle.getCurtain() != "1" && Integer.valueOf(toggle.getCurtain()) % 2 != 0){
                                message.setPayload("3".getBytes());
                            }else if(toggle.getCurtain() != "0" && Integer.valueOf(toggle.getCurtain()) % 2 == 0){
                                message.setPayload("-3".getBytes());
                            }

                            topic.publish(message);

                            topic = mqttClient.getTopic("itgzs/mp3player/older");

                            if("0".equals(toggle.getCurtain())){
                                message.setPayload("13".getBytes());
                            }else if("1".equals(toggle.getCurtain())){
                                message.setPayload("6".getBytes());
                            }else if(toggle.getCurtain() != "1" && Integer.valueOf(toggle.getCurtain()) % 2 != 0){
                                message.setPayload("1".getBytes());
                            }else if(toggle.getCurtain() != "0" && Integer.valueOf(toggle.getCurtain()) % 2 == 0){
                                message.setPayload("11".getBytes());
                            }

                            topic.publish(message);
                        }
                        break;
                    case "itgzs/ir_tran/air_cond/older" :
                        if(!toggle.getDegree().equals(hashMap.get("degree"))){
                            hashMap.put("degree", toggle.getDegree());
                            message.setPayload(toggle.getDegree().getBytes());
                            topic.publish(message);

                            topic = mqttClient.getTopic("itgzs/mp3player/older");
                            if("1".equals(toggle.getDegree())){
                                message.setPayload("4".getBytes());
                            }else if("2".equals(toggle.getDegree())){
                                message.setPayload("5".getBytes());
                            }else if("3".equals(toggle.getDegree())){
                                message.setPayload("16".getBytes());
                            }else if("4".equals(toggle.getDegree())){
                                message.setPayload("17".getBytes());
                            }else if("5".equals(toggle.getDegree())){
                                message.setPayload("18".getBytes());
                            }else if("6".equals(toggle.getDegree())){
                                message.setPayload("19".getBytes());
                            }
                            topic.publish(message);
                        }
                        break;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}